library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Figure 9.7
summary(factor(df$Q21))
summary(factor(df$Q25A))
summary(factor(df$Q11T))
summary(factor(mil_conf.df$Q8a))

# DVs
# Wave 2
df2 <- df[df$Q11<5,]

df2$Q21A <- NA
df2$Q21A[df2$Q21 > 2 & df2$Q21 < 6] <- 0
df2$Q21A[df2$Q21 < 3] <- 1

df2$Q25AA <- NA
df2$Q25AA[df2$Q25A > 2 & df2$Q25A < 6] <- 0
df2$Q25AA[df2$Q25A < 3] <- 1

df2 <- df2[df2$P_ASSIGN1==1,]


# Wave 1
summary(factor(mil_conf.df$Q42A))

mil_conf.df2 <- mil_conf.df

mil_conf.df2$Q42A2 <- NA
mil_conf.df2$Q42A2[mil_conf.df2$Q42A < 6] <- 0
mil_conf.df2$Q42A2[mil_conf.df2$Q42A < 3] <- 1


# Survey Designs
w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2
  )

w1_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight,
    data = mil_conf.df2
  )

f.Q21A <- svyby(~ Q21A, ~Q11T+party, w2_design, svymean, na.rm = TRUE)
f.Q25AA <- svyby(~ Q25AA, ~Q11T+party, w2_design, svymean, na.rm = TRUE)
f.Q42A2 <- svyby(~ Q42A2, ~Q8a+party, w1_design, svymean, na.rm = TRUE)

# 
g.Q21A <- ggplot(f.Q21A, aes(x=factor(party),y=Q21A,fill=factor(Q11T),label=round(Q21A,digits=2)))+
  geom_col(position = position_dodge(1), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Percent Support for Iran Strikes\n")

# Civil War
g.Q25AA <- ggplot(f.Q25AA, aes(x=factor(party),y=Q25AA,fill=factor(Q11T),label=round(Q25AA,digits=2)))+
  geom_col(position = position_dodge(1), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Percent Support for Insurrection Act\n")

g.Q42A2 <- ggplot(f.Q42A2, aes(x=factor(party),y=Q42A2,fill=factor(Q8a),label=round(Q42A2,digits=2)))+
  geom_col(position = position_dodge(1), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Percent Support for Border Mission\n")

grid.arrange(g.Q21A,g.Q25AA, g.Q42A2,ncol=3)
